<?php

namespace backend\models;

use common\service\PubService;
use Yii;
use yii\base\NotSupportedException;
use yii\behaviors\TimestampBehavior;
use yii\db\ActiveRecord;
use yii\web\HttpException;
use yii\web\IdentityInterface;

/**
 * This is the model class for table "basemaster".
 *
 * @property int $MasterId 管理标识
 * @property string $UserName 管理帐号
 * @property string $LoginPass 登录密码
 * @property string $UserPass 备用密码
 * @property int $UserState 帐号状态
 * @property string $LoginDate 登录日期
 * @property int $UserType 账户类别
 * @property string $LoginIP 登录地址
 */
class Basemaster extends ActiveRecord implements IdentityInterface
{
    const STATUS_DELETED = 0;
    const STATUS_ACTIVE = 10;

    public $uchk = true;
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'basemaster';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['UserName', 'LoginPass'], 'required'],
            [['LoginDate'], 'safe'],
            [['UserName', 'LoginPass', 'UserPass'], 'string', 'max' => 32],
            //[['UserState'], 'string', 'max' => 1],
            [['UserType'], 'safe'],
            [['LoginIP'], 'string', 'max' => 15],
        ];
    }

//    public function behaviors()
//    {
//        return [
//            TimestampBehavior::className(),
//        ];
//    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'MasterId' => '管理标识',
            'UserName' => '管理帐号',
            'LoginPass' => '登录密码',
            'UserPass' => '备用密码',
            'UserState' => '帐号状态',
            'LoginDate' => '登录日期',
            'LoginIP' => '登录地址',
            'UserType' => '账户类别',
        ];
    }

    /**
     * @param bool $insert
     * @return bool
     */
    public function beforeSave($insert) {
        if (parent::beforeSave($insert)) {unset($insert);
            if ($this->isNewRecord) {
                $this->LoginDate = date('Y-m-d H:i:m', time());
                $this->LoginIP = PubService::real_ip();
            }
            return true;
        }
        return false;
    }

    /**
     * {@inheritdoc}
     */
    public static function findIdentity($id)
    {
        return static::findOne(['MasterId' => $id, 'UserState' => self::STATUS_DELETED]);
    }

    /**
     * {@inheritdoc}
     */
    public static function findIdentityByAccessToken($token, $type = null)
    {
        throw new NotSupportedException('"findIdentityByAccessToken" is not implemented.');
    }

    /**
     * Finds user by username
     *
     * @param string $username
     * @return static|null
     */
    public static function findByUsername($username)
    {
        return static::findOne(['UserName' => $username]);
    }

    /**
     * Finds user by password reset token
     *
     * @param string $token password reset token
     * @return static|null
     */
    public static function findByPasswordResetToken($token)
    {
        if (!static::isPasswordResetTokenValid($token)) {
            return null;
        }

        return static::findOne([
            'password_reset_token' => $token,
            'status' => self::STATUS_ACTIVE,
        ]);
    }

    /**
     * Finds out if password reset token is valid
     *
     * @param string $token password reset token
     * @return bool
     */
    public static function isPasswordResetTokenValid($token)
    {
        if (empty($token)) {
            return false;
        }

        $timestamp = (int) substr($token, strrpos($token, '_') + 1);
        $expire = Yii::$app->params['user.passwordResetTokenExpire'];
        return $timestamp + $expire >= time();
    }

    /**
     * {@inheritdoc}
     */
    public function getId()
    {
        return $this->getPrimaryKey();
    }

    /**
     * {@inheritdoc}
     */
    public function getAuthKey()
    {
        return '';//$this->auth_key;
    }

    /**
     * {@inheritdoc}
     */
    public function validateAuthKey($authKey)
    {
        return true;//$this->getAuthKey() === $authKey;
    }

    /**
     * Validates password
     *
     * @param string $password password to validate
     * @return bool if password provided is valid for current user
     */
    public function validatePassword($password)
    {
        return Yii::$app->security->validatePassword($password, $this->password_hash);
    }

    /**
     * Generates password hash from password and sets it to the model
     *
     * @param string $password
     */
    public function setPassword($password)
    {
        $this->password_hash = Yii::$app->security->generatePasswordHash($password);
    }


    /**
     * Generates new password reset token
     */
    public function generatePasswordResetToken()
    {
        $this->password_reset_token = Yii::$app->security->generateRandomString() . '_' . time();
    }

    /**
     * Removes password reset token
     */
    public function removePasswordResetToken()
    {
        $this->password_reset_token = null;
    }

    /**
     * Logs in a user using the provided username and password.
     *
     * @return bool whether the user is logged in successfully
     */
    public function login()
    {
        if ($this->validate()) {
            //return Yii::$app->user->login($this->getUser(), $this->uchk ? 3600 * 24 * 30 : 0);
            return Yii::$app->user->login(self::findByUsername($this->UserName), $this->uchk ? 3600 * 24 * 30 : 0);
        }

        return false;
    }


    /**         以下部分为操作用户信息（CURL）
     * *************************************************************************************************************************
     */
    public function getMasterData($page, $pageSize)
    {
        $sql = "select * 
                from basemaster as m 
                left join baserolemaster as r on m.MasterId = r.MasterId 
                left join baserole as br on r.RoleId = br.Id 
                where br.GroupId= 1";//groupid = 1(为系统账号)  2为代理账号
        $data = yii::$app->db->createCommand($sql)->queryAll();
        foreach ($data as $key=>$val){
            $data[$key]['GroupId'] = intval($val['GroupId']);
            $data[$key]['Id'] = intval($val['Id']);
            $data[$key]['MasterId'] = intval($val['MasterId']);
            $data[$key]['Nullity'] = empty($val['Nullity']) ? false : true;
            $data[$key]['Pid'] = intval($val['Pid']);
            $data[$key]['RoleId'] = intval($val['RoleId']);
            $data[$key]['UserState'] = empty($val['UserState']) ? false : true;
            $data[$key]['LoginDate'] = empty($val['LoginDate']) ? '--' : $val['LoginDate'] ;
        }
        return ['data' => $data, 'limit'=> intval($pageSize) , 'page'=> intval($page), 'statusCode'=>200, 'total'=> count($data)];

    }


    public static function getMasterOne($masterId)
    {
        $sql = "select * 
                from basemaster as m 
                left join baserolemaster as r on m.MasterId = r.MasterId 
                left join baserole as br on r.RoleId = br.Id 
                where r.MasterId= {$masterId}";
        $data = yii::$app->db->createCommand($sql)->queryOne();
        if ($data){
            return $data;
        }
        return [];
    }


    public function insertData($post)
    {
        $db = yii::$app->db;
        $transaction  = $db->beginTransaction();
        try {
            $master = new Basemaster();
            $rolemaster = new Baserolemaster();
            $master->UserName = $post['txt_UserName'];
            $master->LoginPass = MD5($post['txt_LoginPass']);
            $master->UserPass = MD5($post['txt_UserPass']);
            $master->LoginIP = PubService::real_ip();
            $master->UserState = isset($post['txt_UserState']) ? 0 : 1;
            if (empty($post['txt_LoginPass']) || empty($post['txt_UserPass'])){
                return ['statusCode' => 300, 'message' => '登录密码和交易密码均不能空'];
            }
            if ($master->save()) {
                $rolemaster->MasterId = $master->MasterId;
                $rolemaster->RoleId = $post['txt_RoleId'];
                if ($rolemaster->save()) {
                    return ['statusCode' => 200, 'message' => '管理帐号信息提交成功'];
                }else{
                    return ['statusCode' => 300, 'message' => '管理帐号信息提交失败'];
                }
            }else{
                return ['statusCode' => 300, 'message' => '管理帐号信息提交失败'];
            }
            $transaction->commit();
            return ['statusCode' => 200, 'message' => '管理帐号信息提交成功'];
        }catch (\Exception $e){
            $transaction->rollBack();
            return ['statusCode' => 300, 'message' => '管理帐号信息提交失败'];
        }
    }


    public function updateData($post)
    {
        $db = yii::$app->db;
        $transaction  = $db->beginTransaction();
        try {
            $master = self::findOne(['MasterId' => $post['txt_ID']]);
            $rolemaster = Baserolemaster::findOne(['MasterId' => $post['txt_ID']]);
            $master->UserName = $post['txt_UserName'];
            if (!empty($post['txt_LoginPass'])){
                $master->LoginPass = MD5($post['txt_LoginPass']);
            }
            if (!empty($post['txt_UserPass'])){
                $master->UserPass = MD5($post['txt_UserPass']);
            }
            $master->UserState = isset($post['txt_UserState']) ? 0 : 1;
//            $master->LoginIP = PubService::real_ip();
//            if (empty($post['txt_LoginPass']) && empty($post['txt_UserPass'])){
//                return ['statusCode' => 300, 'message' => '登录密码和交易密码均不能空'];
//            }
            if ($master->save()) {
                $rolemaster->RoleId = $post['txt_RoleId'];
                if ($rolemaster->save()) {
                    return ['statusCode' => 200, 'message' => '管理帐号信息修改成功'];
                }else{
                    return ['statusCode' => 300, 'message' => '管理帐号信息修改失败'];
                }
            }else{
                return ['statusCode' => 300, 'message' => '管理帐号信息修改失败'];
            }
            $transaction->commit();
            return ['statusCode' => 200, 'message' => '管理帐号信息修改成功'];
        }catch (\Exception $e){
            $transaction->rollBack();
            return ['statusCode' => 300, 'message' => '管理帐号信息修改失败'];
        }
    }


    public function deleteData($post)
    {
        $ids = explode(',', $post['ids']);
        if (in_array(1, $ids)){
            return ['statusCode'=>300, 'message'=>'超级管理帐号禁止删除'];
        }
        $qureya = Basemaster::deleteAll(['in', 'MasterId', $ids]);
        $queryb = Baserolemaster::deleteAll(['in', 'MasterId', $ids]);
        if ($qureya && $queryb){
            return ['statusCode'=>200, 'message'=>'已成功删除管理帐号'];
        }
        return ['statusCode'=>300, 'message'=>'删除管理帐号信息失败'];
    }


    public function changePass($post)
    {
        $passType = $post['passType'];
        $userId = yii::$app->user->getId();
        $master = self::findOne(['MasterId'=>$userId]);
        if (empty($passType)){//登录密码
            $oldPass = $post['ologinpwd'];
            $nloginpwd = $post['nloginpwd'];
            $rnloginpwd = $post['rnloginpwd'];
            if (strtolower($master->LoginPass) != strtolower(md5($oldPass))){
                return ['statusCode'=> 300, 'message'=> '操作失败，原始登录密码错误！'];
            }
            if ($oldPass == $nloginpwd){
                return ['statusCode'=> 300, 'message'=> '操作失败，原始登录密码与重置密码一致！'];
            }
            $master->LoginPass = md5($nloginpwd);
            if ($master->save()){
                return ['statusCode'=> 200, 'message'=> '登录密码重置成功，请重新登录！'];
            }else{
                return ['statusCode'=> 300, 'message'=> '登录密码重置失败，请稍后重试！'];
            }
            return ['statusCode'=> 300, 'message'=> '登录密码重置失败，请稍后重试！'];
        }else{//交易密码
            $ouserpwd = $post['ouserpwd'];
            $nuserpwd = $post['nuserpwd'];
            $rnuserpwd = $post['rnuserpwd'];
            if (strtolower($master->UserPass) != strtolower(md5($ouserpwd))){
                return ['statusCode'=> 300, 'message'=> '操作失败，原始交易密码错误！'];
            }
            if ($ouserpwd == $nuserpwd){
                return ['statusCode'=> 300, 'message'=> '操作失败，原始交易密码与重置密码一致！'];
            }
            if ($rnuserpwd <> $nuserpwd){
                return ['statusCode'=> 300, 'message'=> '操作失败，新密码两次输入不一致！'];
            }
            $master->UserPass = md5($nuserpwd);
            if ($master->save()){
                return ['statusCode'=> 200, 'message'=> '交易密码重置成功，请重新登录！'];
            }
            return ['statusCode'=> 300, 'message'=> '交易密码重置失败，请稍后重试！'];
        }
    }

    /**
     * 通过UserId获取到GroupID
     */
    public static function getGroupId($userId)
    {
        $roleMaster = Baserolemaster::findOne(['MasterId'=>$userId]);
        $roleId = $roleMaster->RoleId;
        $role = Baserole::findOne(['Id'=>$roleId]);
        return $role->GroupId;
    }

    /**
     * 重置密码
     */
    public function chirmpassword($post, $uid)
    {
        $MasterId = $post['txt_Master'];
        if (empty($MasterId)){
            return ['statusCode'=> 300, 'message'=> '网络异常，请稍后重试！'];
        }
        $userid = Baseagency::findOne(['PlayerId'=>$MasterId])->AdminId;
        $master = self::findOne(['MasterId'=>$userid]);
        $ouserpwd = $post['txt_old_Pass'];//新密码
        $nuserpwd = $post['txt_new_Pass'];//重复新密码
        $rnuserpwd = $post['txt_chirm_Pass'];//交易密码
        //当前管理员身份
        if (empty($uid)){
            return ['statusCode'=> 300, 'message'=> '操作失败，请退出重新登录！'];
        }
        $user = self::findOne(['MasterId'=>$uid]);
        if (strtolower($user->UserPass) <> strtolower(md5($rnuserpwd))){
            return ['statusCode'=> 300, 'message'=> '操作失败，管理员交易密码与输入密码不符！'];
        }
        if ($ouserpwd <> $nuserpwd){
            return ['statusCode'=> 300, 'message'=> '操作失败，新密码两次输入不一致！'];
        }
        $master->LoginPass = md5($nuserpwd);
        $master->UserPass = md5($nuserpwd);
        if ($master->save()){
            return ['statusCode'=> 200, 'message'=> '登录密码与交易密码重置成功，请重新登录！'];
        }
        return ['statusCode'=> 300, 'message'=> '密码重置失败，请稍后重试！'];
    }

    public function editMobile($post, $uid)
    {
        $MasterId = $post['txt_Master'];
        if (empty($MasterId)){
            return ['statusCode'=> 300, 'message'=> '网络异常，请稍后重试！'];
        }
        $mobile = $post['txt_mobile'];//手机号码
        $rnuserpwd = $post['txt_chirm_Pass'];//交易密码
        //当前管理员身份
        if (empty($uid)){
            return ['statusCode'=> 300, 'message'=> '操作失败，请退出重新登录！'];
        }
        $user = self::findOne(['MasterId'=>$uid]);
        if (strtolower($user->UserPass) <> strtolower(md5($rnuserpwd))){
            return ['statusCode'=> 300, 'message'=> '操作失败，管理员交易密码与输入密码不符！'];
        }
        $agent = Baseagency::findOne(['PlayerId'=>$MasterId]);
        if (!$agent){
            return ['statusCode'=> 300, 'message'=> '操作失败，此账号不是代理身份玩家！'];
        }
        $agent->Mobile = $mobile;
        if ($agent->save()){
            return ['statusCode'=> 200, 'message'=> '手机号码重置成功！'];
        }
        return ['statusCode'=> 300, 'message'=> '手机号码重置失败！'];
    }
}
